package org.benjamin.sso.controller;

import java.util.List;

import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.benjamin.sso.domain.entity.RegisteredService;
import org.benjamin.sso.repository.RegisteredServiceRepository;
import org.benjamin.sso.service.RegisteredServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "manager")
public class ManagerController {
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private RegisteredServiceRepository registeredServiceRepository;
	
	@Autowired
	private RegisteredServiceService registeredServiceService;
	
	@RequestMapping(value = "index")
	private String index(ModelMap modelMap) throws IllegalAccessException {
		List<RegisteredService> registeredServices = this.registeredServiceRepository.findAll();
		modelMap.addAttribute("registeredServices",registeredServices);
		return "manager/index";
	}
	
	@RequestMapping(value = "details/{id}")
	public String details(@PathVariable("id")Integer id,ModelMap modelMap) {
		RegisteredService registeredService = this.registeredServiceRepository.findOne(id);
		modelMap.addAttribute(registeredService);
		return "manager/add";
	}
	
	@GetMapping(value = "add")
	public String add(ModelMap modelMap) {
		modelMap.addAttribute("registeredService",new RegisteredService());
		return "manager/add";
	}
	
	@PostMapping(value = "save")
	public String save(@Valid RegisteredService registeredService,BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			
		}else {
			logger.debug("将服务信息保存数据库中:{}",registeredService);
			try {
				this.registeredServiceService.saveRegisteredService(registeredService);	
			}catch (AuthorizationException e) {
				logger.warn(e.getMessage());
				throw e;
			}
			
		}
		return "";
	}

}
